<template>
  <div v-if="visible">
    <j-modal
      switchFullscreen
      :title="config.title"
      :width="config.width||1200"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭">
      <template slot="footer">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleOk" v-if="!disableSubmit">确认</a-button>
      </template>
      <a-divider :orientation="config.divider.location" v-if="config.divider"> {{ config.divider.name }}</a-divider>
      <a-spin :spinning="confirmLoading">
        <a-form :form="form">
          <a-row :gutter="24">
          <span v-for="(item,index) in config.list" :key="index">
          <a-col v-if="item.show!==false" :span="item.span||24" :md="item.md||24" :sm="item.sm||24">
            <a-form-item
              :labelCol="item.labelCol||config.labelCol||labelCol"
              :wrapperCol="item.wrapperCol||config.wrapperCol||wrapperCol"
              :label="item.label||''"
            >
              <!--              输入框-->
              <a-input v-if="item.type=='input'" :type="item.inputType||'text'" :disabled="item.disabled||false"
                       :placeholder="item.placeholder||''" v-decorator="[item.name, item.check||{}]"/>

              <a-input-password v-if="item.type=='input-password'" :disabled="item.disabled||false"
                                :placeholder="item.placeholder||''" v-decorator="[item.name, item.check||{}]"/>
              <a-input-number v-if="item.type=='input-number'" :disabled="item.disabled||false" :min="item.min"
                              :max="item.max"
                              :placeholder="item.placeholder||''" v-decorator="[item.name, item.check||{}]"
                              style="width: 100%"/>
              <!--            自定义选择框-->
              <a-input-search v-if="item.type=='input-search'" v-decorator="[item.name, item.check||{}]" :disabled='item.disabled||false'
                               readOnly enter-button @search="custSearch(item.status,item.formconfig,item.tableconfig,item.name,item.code)" />
              <a-textarea v-if="item.type=='textarea'" :maxLength="500" :placeholder="item.placeholder||''"
                          :disabled="item.disabled||false" v-decorator="[item.name, item.check||{}]"/>
              <!--              <a-switch v-if="item.type=='switch'" v-decorator='[item.name, item.check||{}]'-->
              <!--                        :disabled='item.disabled||false' :checkedValue='1'-->
              <!--                        :unCheckedValue='0' />-->

              <vxe-switch v-if="item.type=='switch'"
                          v-model="model[item.name]"
                          :open-value="item.openvalue||1"
                          :close-value="item.closevalue||0"></vxe-switch>
              <!--              省市区-->
              <j-area-linkage v-if="item.type=='area'"  v-decorator="[item.name, item.check||{}]" :placeholder="item.placeholder" type="cascader"
                               :province.sync="form.provinceName" :disabled="item.disabled||false"
                               :city.sync="form.city" :area.sync="form.area" @change="handlePca"/>
              <!--              字典下拉框-->
              <cn-dict-select-tag v-if="item.type=='j-select'"
                                  :options="{value:'dictDataCode',label:'dictDataDesc'}"
                                  :triggerChange="true"
                                  :dictCode="item.dictCode" :disabled="item.disabled||false"
                                  v-decorator="[item.name, item.check||{}]" :placeholder="item.placeholder"
                                  @change="(e,v)=>changeJselect(item.name,v,item.fun)"/>
              <cn-multi-select-tag v-if="item.type=='j-multi-select'"
                                   :dictCode="item.dictCode" :disabled="item.disabled||false"
                                   v-decorator="[item.name, item.check||{}]" :placeholder="item.placeholder"
              />
              <!--              自定义单选下拉框-->
              <a-select v-if="item.type=='a-select'"
                        v-decorator="[item.name, item.check||{}]" :disabled="item.disabled||false"
                        :placeholder="item.placeholder"
                        @change="changeSelect(item.option,item.name,$event,item.fun)"
              >
                    <a-select-option v-for="(v,i) in item.option" :key="i" :value="v.value">
                     {{ v.name }}
                    </a-select-option>
              </a-select>
              <!--              自定义多选下拉框-->
              <cn-multi-select-tag
                v-if="item.type=='a-select-multiple'"
                v-decorator="[item.name, item.check||{}]"
                :placeholder="item.placeholder"
                :options="item.option"
                @change="changeSelect(item.option,item.name,$event,item.fun)"
              ></cn-multi-select-tag>


              <!--              自定义单选框-->
              <a-radio-group v-if="item.type=='a-radio'" v-decorator="[item.name, item.check||{}]"
                             :placeholder="item.placeholder" :disabled="item.disabled||false">
                    <a-radio v-for="(v,i) in item.option" :key="i" :value="v.value">
                      {{ v.name }}
                    </a-radio>
              </a-radio-group>
              <!--              树形选择-->
              <j-tree-select ref="selectRef" v-if="item.type=='tree-select'"
                             :placeholder="item.placeholder" :disabled="item.disabled||false"
                             v-decorator="[item.name, item.check||{}]"
                             :data-type="item.dataType"/>
              <!--              图片上传-->
              <j-image-upload v-if="item.type=='upload'" class="avatar-uploader" :text="item.text"
                              :disabled="item.disabled||false"
                              v-decorator="[item.name, item.check||{}]"></j-image-upload>
              <!--              日期-->
              <j-date v-if="item.type=='date'" :placeholder="item.placeholder" :disabled="item.disabled||false"
                      format="YYYY-MM-DD" v-decorator="[ item.name, item.check||{}]" style="width:100%"/>
              <j-markdown-editor v-if="item.type=='markdown'" :placeholder="item.placeholder"
                                 :disabled="item.disabled||false"
                                 v-decorator="[ item.name, item.check||{}]"></j-markdown-editor>
              <!--           日期范围选择-->
              <span v-if="item.type=='date-double'" style="display: flex;align-items: center">
                <a-date-picker :placeholder="item.placeholder[0]||''" :disabled="item.disabled||false"
                               format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"
                               v-decorator="[ item.name[0], item.check||{}]" style="width:100%"/>
                 <span style="margin: 0 10px">~</span>
                <a-date-picker :placeholder="item.placeholder[1]||''" :disabled="item.disabled||false"
                               format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"
                               v-decorator="[ item.name[1], item.check||{}]" style="width:100%"/>
              </span>

              <a-range-picker v-if="item.type=='date-range'" :placeholder="item.placeholder||[]"
                              :disabled="item.disabled||false"
                              format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" v-decorator="[ 'date',item.check||{}]"
                              @change="(e)=>dateRangeChange(e,item.range)"
              />
              <!--           自定义上传选择-->
              <j-upload v-if="item.type=='j-upload'"  :returnUrl="false"  class="avatar-uploader" buttonVisible
                        v-decorator="[item.name, item.check||{}]" :file-type="item.fileType"
                        @change="(url,filelist)=>uploadChange(url,filelist,item.fun,item.name)"
                        :disabled="item.disabled"></j-upload>
              <!--           角色选择-->
              <j-select-role v-if="item.type=='j-role'" :giveBackList="model.customers"
                             :rowKey="'roleCode'" :roleCodes=form.getFieldValue(item.name2)
                             v-decorator="[ item.name, item.check||{}]" :multiple="item.multiple"
                             :disabled="item.disabled" @select="(row)=>selectRole(row,item.name,item.name2)"/>
              <a-input type="hidden" v-if="item.type=='j-role' && item.name2" v-decorator="[ item.name2]"></a-input>
              <J-select-cust v-if="item.type=='j-cust'"
                             v-decorator="[ item.name, item.check||{}]"
                             :disabled="item.disabled"
                             :multiple="item.multiple"
                             @select="(row)=>custSeleC(row,item.name,item.multiple)"
              ></J-select-cust>

              <j-select-database v-if="item.type=='j-database'"
                                 v-decorator="[ item.name, item.check||{}]"
                                 :disabled="item.disabled"
                                 :multiple="item.multiple"
                                 @select='(row)=>custSeleC(row,item.name,item.multiple,"database")'></j-select-database>
              <a-input type="hidden" v-if="item.type=='j-database' && item.name2"
                       v-decorator="[ item.name2]"></a-input>
            </a-form-item>
            <!--              穿梭框-->
            <div v-if="item.type == 'transfer'">
              <a-transfer
                :data-source="mockData"
                :target-keys="targetKeys"
                :disabled="false"
                :show-search="false"
                :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
                :show-select-all="false"
                style="display: flex;justify-content: center;align-items: center"
                :listStyle="{border:'1px solid #ebedf0',height:'500px',padding:'10px',boxSizing:'border-box',margin:'10px',borderRadius:'8px',width:'50%'}"
                @change="onChange"
              >
                <template
                  slot="children"
                  slot-scope="{
                  props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
                  on: { itemSelectAll, itemSelect },
                 }"
                >
                    <a-table
                      :row-selection="
                        getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
                      "
                      :columns="direction === 'left' ? leftColumns : rightColumns"
                      :data-source="filteredItems"
                      size="small"
                      :style="{ pointerEvents: listDisabled ? 'none' : null}"
                      :custom-row="
                         ({ key, disabled: itemDisabled }) => ({
                          on: {
                            click: () => {
                              if (itemDisabled || listDisabled) return;
                              itemSelect(key, !selectedKeys.includes(key));
                            },
                          },
                        })
                      "
                      :ipagination="ipagination"
                      @change="handleTableChange"
                    />
                  </template>
              </a-transfer>
              </div>
          </a-col>
          </span>
          </a-row>
        </a-form>
      </a-spin>
      <proChose ref="prochoose" :name='title2' @okbro="okbropro"></proChose>
    </j-modal>
  </div>
</template>
<script>
import CnMultiSelectTag from '@comp/dict/CnMultiSelectTag'
import { getAction, postAction } from '@api/manage'
import { pick } from 'lodash'
import JDate from '@comp/cn-form/JDate'
import moment from 'moment'
import proChose from '@comp/cn-components/ProChose'
import JTreeSelect from '@comp/cn-form/JTreeSelect'
import JAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import UploadImage from '@comp/upload-image/UploadImage'
import JImageUpload from '@comp/cn-form/JImageUpload'
import JMarkdownEditor from '@comp/cn-form/cnMarkdownEditor'
import Area from '@comp/utils/Area'
import JUpload from '@comp/cn-form/JUpload'
import JSelectRole from '@comp/cn-select-popup/JSelectRole'
import JSelectCust from '@comp/cn-select-popup/CnSelectCust'
import JSelectDatabase from '@comp/cn-select-popup/JSelectDatabase'
import JSelectMultiple from '@comp/cn-form/JSelectMultiple'
import { login } from '@api/login'

const mockData = []

const leftTableColumns = [
  {
    dataIndex: 'title',
    title: '门店名称'
  },
  {
    dataIndex: 'description',
    title: '门店编号'
  }
]
const rightTableColumns = [
  {
    dataIndex: 'title',
    title: '门店名称'
  },
  {
    dataIndex: 'description',
    title: '门店编号'
  }
]
export default {
  name: 'popup-modal',
  data() {
    return {
      disableSubmit: false,
      mockData,
      targetKeys: [],
      accept: '',
      leftColumns: leftTableColumns,
      rightColumns: rightTableColumns,
      selectedRowKeys: [],
      selectedRowKeys1: [],
      sendPro: false,
      ProductAdress: [],
      dataSurces2: [],
      formChoice: [],
      showCode: false,
      remembertext: '',
      dataSource: [],
      manobjList: [0],
      areaData: '',
      areaLinkage: '',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      config: {},
      addOrUpdateUrl: window._CONFIG['domianURL'] + '/cnTerminalController/saveOrUpdateTerminal',
      list: window._CONFIG['domianURL'] + '/cnTerminalController/custFindTerminalList',
      getCustmen: window._CONFIG['domianURL'] + '/terminal/cnRTermPtPos/findCustCodeForUserPos'
    }
  },
  components: {
    JTreeSelect,
    JAreaLinkage,
    UploadImage,
    JImageUpload,
    JDate,
    JMarkdownEditor,
    JUpload,
    JSelectRole,
    JSelectCust,
    JSelectDatabase,
    CnMultiSelectTag,
    JSelectMultiple,
    proChose
  },
  created() {
    this.initAreaData()

    // console.log(this.areaData);
  },
  mounted() {
    // this.getMock();
  },
  methods: {

    handlePca(code,code2) {
      this.model.provinceName = this.areaData.getText(code).split('/')[0]
      this.model.cityName = this.areaData.getText(code).split('/')[1]
      this.model.areaName = this.areaData.getText(code).split('/')[2]
      this.model.provinceCode = code2[0]
      this.model.cityCode = code2[1]
      this.model.areaCode = code2[2]
    },
    randomHexColor() { //随机生成十六进制颜色
      var hex = Math.floor(Math.random() * 16777216).toString(16) //生成ffffff以内16进制数
      while (hex.length < 6) { //while循环判断hex位数，少于6位前面加0凑够6位
        hex = '0' + hex
      }
      return '#' + hex //返回‘#'开头16进制颜色
    },

    add(config) {
      this.edit({}, config)
    },
    // config(config) {
    //   this.config = config
    // },
    edit(record, config) {
      this.form.resetFields()
      this.config = config
      this.ProductAdress = []
      this.form.resetFields()
      this.model = Object.assign({}, record)
      // this.model.roleList = this.returnList(this.model.roleNames, this.model.roleCodes + '', 'roleName', 'roleCode')
      this.visible = true
      this.$nextTick(() => {
        this.loadData(1)
        this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
      })
    },

    // 数组
    returnList(names = '', codes = '', name = '', code = '') {
      let list = []
      if (names && codes) {
        names = names.split(',')
        codes = codes.split(',')
        for (let i = 0; i < names.length; i++) {
          list.push({
            [name]: names[i],
            [code]: codes[i]
          })
        }
      }
      return list
    },

    close() {
      this.$emit('close')
      this.visible = false
      this.form.resetFields()
      // this.$refs.selectRef.treeValue=null
    },
    //自定义选择框回显
    okbropro(val, status, status2) {
      let objs = JSON.parse(JSON.stringify(val[0]))
      console.log(status,objs)
      if(status=='Products'){
        this.form.setFieldsValue({
          productCode: objs.goodsCode,
          productName: objs.goodsName,
          // stockUnit: objs.basicUnit,
          basicUnit: objs.basicUnit,
        })
      }
      if(status=='Pickuppoint'){
        this.form.setFieldsValue({
          pupCode: objs.pupCode,
          pupName: objs.pupName,
          // stockUnit: objs.basicUnit,
          // basicUnit: objs.basicUnit,
        })
      }
    },
    //自定义选择框传入值
    custSearch(status,formconfig,tableconfig,name,code) {
      this.$refs.prochoose.rowKey=name
      let dataSource = []
      if(this.form.getFieldValue(name)){
        dataSource = [{
          name:this.form.getFieldValue(name),
          code:this.form.getFieldValue(code)
        }]
      }
      this.$refs.prochoose.edit(formconfig, tableconfig, status,'status2',dataSource)
    },
    loadData(arg) {
      if (!this.reqTerminal) {
        // this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = {}
      params.current = this.ipagination.current
      params.size = this.ipagination.pageSize
      //查询条件
      this.loading = true
      let request = null
      const isNoPagnation = ['getDictByCode'].some(url => new RegExp(`${url}$`).test(this.reqTerminal))
      if (isNoPagnation) {
        request = getAction
      } else {
        request = postAction
      }
      var that = this
      return request(this.reqTerminal, params).then((res) => {
        if (res.success) {
          that.mockData = isNoPagnation ? res.result : res.result.records
          if (!isNoPagnation) that.ipagination.total = res.result.total || 0
        } else {
          that.$message.warning(res.message)
        }
        that.loading = false
      })
      // }
    },

    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },

    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)
          console.log(values.roleNames)
          if (!this.config.addOrUpdateUrl) {
            that.$emit('ok', formData)
            return
          }

          if (this.config.method == 'get') {
            getAction(this.config.addOrUpdateUrl, formData).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
          } else {
            postAction(this.config.addOrUpdateUrl, formData).then((res) => {
              if (res.success) {
                that.$message.success(res.message, 2)
                that.$emit('ok')
                that.close()
              } else {
                that.$message.error(res.message, 2)
              }
            }).finally(() => {
              that.confirmLoading = false
            })
          }
        }
      })
    },

    handleCancel() {
      this.close()
    },

    initAreaData() {
      if (!this.areaData) {
        this.areaData = new Area()
      }
    },

    changeSelect(options, name, event, fun) {
      if (fun) {
        this.$emit(fun, event)
      }
      name = name.split('Code')
      if (name.length > 1) {
        name = name[0] + 'Name' + (name[1] ? name[1] : '')
        let item = options.find(item => item.value == event)
        this.model[name] = item.name
      }
    },

    changeJselect(name, value, fun) {
      if (fun) {
        this.$emit(fun, value)
      }
      name = name.split('Code')
      this.model[name + 'Name'] = value.dictDataDesc
      if (name.length > 1) {
        name = name[0] + 'Name' + (name[1] ? name[1] : '')
        this.model[name] = value.dictDataDesc
      }
    },
    custSeleC(row, name, e3, flag = 'cust') {
      console.log(row)
      if (e3) {
        let code = row.map(item => {
          return item.custCode
        })
        this.form.setFieldsValue({
          custCode: code
        })
      } else {
        if (flag == 'cust') {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              custCode: row[0].custCode
            })
            this.form.setFieldsValue({
              custName: row[0].custName
            })
          })
          return
        }
        if (flag == 'database') {
          // debugger
          // this.$nextTick(()=>{
          this.form.setFieldsValue({
            configId: row[0].id
          })
          // })

        }

      }

      // let codes = row.map(item => {
      //   return item.roleCode
      // }).join(',')
      // this.form.setFieldsValue({
      //   [name2]: codes
      // })
    },
    selectRole(row, name, name2) {
      console.log(row, name, name2)
      let codes = row.map(item => {
        return item.roleCode
      }).join(',')
      let names = row.map(item =>{
        return item.roleName
      }).join(',')
      this.form.setFieldsValue({
        [name]: codes,
        [name2]: names
      })
    },

    onChange(nextTargetKeys) {
      this.targetKeys = nextTargetKeys
    },

    triggerDisable(disabled) {
      this.disabled = disabled
    },

    triggerShowSearch(showSearch) {
      this.showSearch = showSearch
    },

    getRowSelection({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter(item => !item.disabled)
            .map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)
          itemSelectAll(diffKeys, selected)
        },
        onSelect({ key }, selected) {
          itemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys
      }
    },

    uploadChange(url, fileList, fun, name) {
      console.log('这是中转站')
      if (fun) {
        this.$emit(fun, fileList)
      }
      fileList.forEach(item => item.fileName = item.name)
      this.form.setFieldsValue(name, fileList)
    },

    dateRangeChange(date, name) {
      if (!date) {
        this.model[name[0]] = ''
        this.model[name[1]] = ''
        return
      }
      this.model[name[0]] = date[0]
      this.model[name[1]] = date[1]
    }
  }
}
</script>

<style scoped>
.gonghuoxinxi {
  width: 100%;
  border-bottom: 1px dashed black;
  margin: 10px 0;
  padding: 15px 5px;
  display: flex;
  flex-direction: column;
}

.two-table {
  width: 100%;
  display: flex !important;
  justify-content: space-around;
}

/deep/ .ant-transfer-operation {
  display: flex;
  flex-direction: column;
}

/deep/ .ant-btn-icon-only {
  margin: 10px;
}
/deep/ .ant-col-sm-3-1{
  width: 14.2%;
}
/deep/ .ant-col-sm-21-1{
  width: 84%;
}

</style>
